//
//  StoryList.m
//  iPing
//
//  Created by Thomas on 8/6/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "SGStoryList.h"
#define myDomain			(CFStringRef)@"com.tomcool.storyGrabber"
#import "TCSGStory.h"

@implementation SGStoryList
- (void)setManagedObjectContext:(NSManagedObjectContext *)moc
{
	[moc retain];
	[managedObjectContext release];
	managedObjectContext = moc;
}
+(NSDictionary *)dictForKey:(NSString *)theKey
{
	NSDictionary * myDict = [(NSDictionary *)CFPreferencesCopyAppValue((CFStringRef)theKey, myDomain) autorelease];
	return (NSDictionary *)myDict;
}
+ (void)setDict:(NSDictionary *)inputDict forKey:(NSString *)theKey
{
	CFPreferencesSetAppValue((CFStringRef)theKey, (CFDictionaryRef)inputDict, myDomain);
	CFPreferencesAppSynchronize(myDomain);
	
	//CFRelease(inputDict);
}
-(id)init
{
	self = [super init];
	orderedList	= [[NSMutableArray alloc] init];
	[orderedList retain];
	dataDict	= [[NSMutableDictionary alloc] init];
	lastStoryID	= [[NSString alloc] init];
	i=-1;
	return self;
}
-(void)addStory:(NSString *)story 
	  withTitle:(NSString *)title 
	 withAuthor:(NSString *)author 
	   withHost:(NSString *)host 
		 withID:(NSString *)IDNumber 
	  withCheck:(NSNumber *)checkVal
   withHTMLCode:(NSString *)HTMLCode
{
	story = [story stringByReplacingOccurrencesOfString:@"Ôªø" withString:@""];
	
	i++;
	NSDictionary *tempdict = [NSDictionary dictionaryWithObjectsAndKeys:
							  story,STORYKEY,
							  author,AUTHORKEY,
							  title,TITLEKEY,
							  host,HOSTKEY,
							  checkVal,CHECKKEY,
							  IDNumber,IDKEY,
							  nil];
	NSString *temphost=@"";
	if([host isEqualToString:@"StoriesOnline"])
	{
		temphost=@"SOL";
	}
	else if([host isEqualToString:@"Ficwad.com"])
	{
		temphost=@"FW";
	}
	else
	{
		temphost=@"LIT";
	}
	lastStoryID = nil;
	[lastStoryID release];
	lastStoryID	=HTMLCode;
	[lastStoryID retain];
	if([orderedList containsObject:lastStoryID])
	{
		[orderedList removeObject:lastStoryID];
		[dataDict removeObjectForKey:lastStoryID];
	}
	[orderedList addObject:HTMLCode];
	NSLog(@"orderedList1: %@",orderedList);
	[dataDict setObject:tempdict forKey:HTMLCode];
}
-(void)addStori:(NSString *)story 
	  withTitle:(NSString *)title 
	 withAuthor:(NSString *)author 
	   withHost:(NSString *)host 
		 withID:(NSString *)IDNumber 
	  withCheck:(NSNumber *)checkVal
{
	NSLog(@"here");
	story = [story stringByReplacingOccurrencesOfString:@"Ôªø" withString:@""];

	i++;
	NSDictionary *tempdict = [NSDictionary dictionaryWithObjectsAndKeys:
							  story,STORYKEY,
							  author,AUTHORKEY,
							  title,TITLEKEY,
							  host,HOSTKEY,
							  checkVal,CHECKKEY,
							  IDNumber,IDKEY,
							  nil];
	NSString *temphost=@"";
	if([host isEqualToString:@"StoriesOnline"])
	{
		temphost=@"SOL";
	}
	else if([host isEqualToString:@"Ficwad.com"])
	{
		temphost=@"FW";
	}
	else
	{
		temphost=@"LIT";
	}
	lastStoryID = nil;
	[lastStoryID release];
	lastStoryID	=[NSString stringWithFormat:@"%@_%@",temphost,IDNumber,nil];
	[lastStoryID retain];
	if([orderedList containsObject:lastStoryID])
	{
		[orderedList removeObject:lastStoryID];
		[dataDict removeObjectForKey:lastStoryID];
	}
	[orderedList addObject:[NSString stringWithFormat:@"%@_%@",temphost,IDNumber,nil]];
	NSLog(@"orderedList1: %@",orderedList);
	[dataDict setObject:tempdict forKey:[NSString stringWithFormat:@"%@_%@",temphost,IDNumber,nil]];
}
-(NSString *)getLastStory
{
	NSLog(@"hello");
	NSLog(@"%@",lastStoryID);
	return [[dataDict objectForKey:lastStoryID] objectForKey:STORYKEY];
}
-(NSString *)getLastTitle
{
	return [[dataDict objectForKey:lastStoryID] objectForKey:TITLEKEY];
}
-(id)getDictForRow:(int)row
{
	NSString *key = [orderedList objectAtIndex:row];
	return [dataDict objectForKey:key];
}
-(NSString *)getTOCforRow:(int)row
{
	NSString *key = [orderedList objectAtIndex:row];
	NSDictionary *tempdict = [dataDict objectForKey:key];
	NSString *tempTOC=@"";
	if([[tempdict objectForKey:CHECKKEY] boolValue])
	{
		NSString *	 summary=@"Not Available";
		NSString *	 codes=@"Not Available";
		if([[tempdict allKeys] containsObject:SUMMARYKEY])
		{
			summary = [tempdict objectForKey:SUMMARYKEY];
		}
		if([[tempdict allKeys] containsObject:CODESKEY])
		{
			codes = [tempdict objectForKey:CODESKEY];
		}
		tempTOC = [NSString stringWithFormat:@"<h2 class=\"chapter\"><a href='#%i'>%@</a></h2>\n<br>\n<h3>Author:</h3>%@<br><h3>Synopsis:</h3>%@<br>\n<h3>Codes:</h3>%@<br>",
							 row,
							 [tempdict objectForKey:TITLEKEY],
							 [tempdict objectForKey:AUTHORKEY],
							 [tempdict objectForKey:SUMMARYKEY],
							 [tempdict objectForKey:CODESKEY],
							 nil];		
	}
		return tempTOC;
}
-(NSString *)getTOC
{
	int ii;
	NSString *longTOC = @"<h1 class=\"chapter\">Table Of Contents</h1>\n";
	for(ii=0;ii<[orderedList count];ii++)
	{
		NSString *tempTOC = [self getTOCforRow:ii];
		longTOC = [NSString stringWithFormat:@"%@\n\n\n<br><br>%@",longTOC,tempTOC,nil];
	}
	
	return longTOC;
	
}
-(NSString *)combineAll
{
	NSString *toc = [self getTOC];
	NSString *stories = [NSString stringWithString:toc];
	int ii;
	for(ii=0;ii<[orderedList count];ii++)
	{
		NSString *key = [orderedList objectAtIndex:ii];
		NSDictionary *tempdict = [dataDict objectForKey:key];
		if([[tempdict objectForKey:CHECKKEY] boolValue])
		{
			NSString *tempStory = [tempdict objectForKey:STORYKEY];
			tempStory = [tempStory stringByReplacingOccurrencesOfString:@"<h1 class=\"Chapter\"" withString:[NSString stringWithFormat:@"<h1 class=\"Chapter\" id=\"%i\"",ii]];
			stories = [NSString stringWithFormat:@"%@<br><br>\n\n%@",stories,tempStory];
		}
	}
	return stories;
}
-(void)moveItemAtRow:(int)row value:(int)action
{
	if((action < 0 && action+row>=0) || (action > 0 && action+row<[orderedList count]))
	{
		[orderedList exchangeObjectAtIndex:row withObjectAtIndex:(action+row)];
	}
}
-(void)removeItemAtRow:(int)row
{
	NSString *obj = [orderedList objectAtIndex:row];
	[orderedList removeObjectAtIndex:row];
	[dataDict removeObjectForKey:obj];
}
-(void)switchCheck:(NSString *)checkName forRow:(int)row
{
	NSString *obj = [orderedList objectAtIndex:row];
	NSMutableDictionary *tempdict = [[dataDict objectForKey:obj] mutableCopy];
	BOOL boolVal = [[tempdict objectForKey:checkName] boolValue];
	[tempdict setObject:[NSNumber numberWithBool:!boolVal] forKey:checkName];
	[dataDict setObject:tempdict forKey:obj];
	//return !boolVal;
}
-(BOOL)checkForRow:(int)row withKey:(NSString *)checkName
{
	NSString *obj = [orderedList objectAtIndex:row];
	NSMutableDictionary *tempdict = [[dataDict objectForKey:obj] mutableCopy];
	return [[tempdict objectForKey:checkName] boolValue];
}
-(void)printDict
{
	NSLog(@"ordered: %@",orderedList);
	NSLog(@"datadict: %@",dataDict);
	[dataDict writeToFile:@"/Users/tom/Desktop/hello.plist" atomically:YES];
}
-(int)numberOfItems
{
	NSLog(@"orderedList2: %@",orderedList);
	return [orderedList count];
}
- (void)addExtraInfo:(NSDictionary *)extraInfo forRow:(int)row
{
	NSString *obj = [orderedList objectAtIndex:row];
	NSMutableDictionary *tempdict = [[dataDict objectForKey:obj] mutableCopy];
	[tempdict addEntriesFromDictionary:extraInfo];
	[dataDict setObject:tempdict forKey:obj];
	//[dataDict writeToFile:@"/Users/tom/hello.plist" atomically:YES];
}
- (void)addAddionalInfo:(NSDictionary *)storyDict forRow:(int)row
{
	NSMutableDictionary *dict = [storyDict mutableCopy];
	[dict removeObjectsForKeys:[NSArray arrayWithObjects:STORYKEY,AUTHORKEY,HOSTKEY,IDKEY,HTMLCODEKEY,TITLEKEY,nil]];
	NSString *obj = [orderedList objectAtIndex:row];
	NSMutableDictionary *tempdict = [[dataDict objectForKey:obj] mutableCopy];
	[tempdict addEntriesFromDictionary:dict];
	[dataDict setObject:tempdict forKey:obj];
}
- (void)addCheckedToLibrary
{
	[TCSGGeneralMethods checkBundleExistance];
	NSLog(@"1");
	NSMutableDictionary *db = [[TCSGGeneralMethods getDB] mutableCopy];
	NSMutableDictionary *helloDict = [dataDict mutableCopy];
	NSArray *helloArray = [helloDict allKeys];
	int ii;
	NSLog(@"2");
	for(ii=0;ii<[helloArray count];ii++)
	{
		NSMutableDictionary *tempdict = [helloDict objectForKey:[helloArray objectAtIndex:ii]];
		
		if([[tempdict objectForKey:CHECKKEY] boolValue])
		{
			if([TCSGGeneralMethods SaveIndividualChapters])
			{
				[[tempdict objectForKey:ARRAYKEY] writeToFile:[TCSGGeneralMethods plistPathForHTMLCode:[helloArray objectAtIndex:ii]] atomically:YES];
			}
			NSLog(@"before");
			[tempdict setObject:[NSNumber numberWithInt:[[tempdict objectForKey:ARRAYKEY] count]] forKey:LASTDOWNLOADEDCHAPTER];
			NSLog(@"lastDownloadedChapter: %i",[[tempdict objectForKey:ARRAYKEY] count]);
			[[tempdict objectForKey:STORYKEY] writeToFile:[TCSGGeneralMethods fullStoryPathForHTMLCode:[helloArray objectAtIndex:ii]] atomically:YES encoding:NSUTF8StringEncoding error:nil];
			[tempdict removeObjectForKey:ARRAYKEY];
			[tempdict removeObjectForKey:STORYKEY];
			//[tempdict setObject:[NSNumber numberWithInt:lastDownloadedChapter] forKey:LASTDOWNLOADEDCHAPTER];
			[db setObject:tempdict forKey:[helloArray objectAtIndex:ii]];
			[TCSGStory storyFromDictionary:tempdict withName:[helloArray objectAtIndex:ii] inManagedObjectContext:managedObjectContext];

		}
	}
	NSError *error = nil;
    if (![managedObjectContext save:&error]) {
        [[NSApplication sharedApplication] presentError:error];
    }
	//[[NSNotificationCenter defaultCenter] postNotificationName:@"Add to Controller" object:toAdd];
	NSLog(@"3");
	[TCSGGeneralMethods writeDB:db];
	NSLog(@"4");
	/*NSString *mBundleID = [[[NSBundle bundleForClass:[self class]] bundleIdentifier] stringByAppendingString:@".db"];
	[[NSUserDefaults standardUserDefaults] registerDefaults: helloDict]; 
	//[NSUserDefaults synchronize];
	[[NSUserDefaults standardUserDefaults] setPersistentDomain:helloDict forName:mBundleID];
	//[self setDict:helloDict forKey:@"storyDB"];*/
}
@end
